from asyncore import read
from copy import copy
from datetime import datetime
from io import StringIO
import json
import os
import sys
import time
import psycopg2

from data_reader.DataReader import DataReader
from data_reader.NsReader import NsReader
from data_reader.OrReader import OrReader
from utils.Timer import Timer

def connect():
    conn = psycopg2.connect("dbname=postgres user=postgres password=postgres")
    return conn.cursor()

def query_circle(table, x, y, radius):
    cur = connect()
    cur.exec('''
        SELECT * FROM %s
        (SELECT * FROM  WHERE
        (x between %f and %f) and
        (y between %f and %f) )
        WHERE (x-%f)^2 + (y-%f)^2 < (%f)^2
    '''%(table, x-radius, x+radius, y-radius, y+radius, radius))

def query_rect(table, x_min, x_max, y_min, y_max):
    cur = connect()
    cur.exec('''
        SELECT * FROM %s WHERE
        (x between %f and %f) and
        (y between %f and %f)
    '''%(table, x_min, x_max, y_min, y_max))

def query_sweep(table, sweep_index):
    cur = connect()
    cur.exec('''
        SELECT * FROM %s WHERE
        sweep = %d
    '''%(table, sweep))

def query_timestamp(table, tstamp_start, tstamp_end):
    cur = connect()
    cur.exec('''
        SELECT * FROM %s WHERE
        tstamp between %s and %s
    '''%(table, datetime.fromtimestamp(tstamp_start), datetime.fromtimestamp(tstamp_end)))

def query_classification(table, cls):
    cur = connect()
    cur.exec('''
        SELECT * FROM %s WHERE
        cls = %d
    '''%(table, cls))


if __name__ == '__main__':
    query_circle("point_cloud", 100, 100)
    query_circle("point_cloud", 100, 100)
    query_rect("point_cloud", 100, 100)
    query_rect("point_cloud", 100, 100)
    query_sweep("point_cloud", 1)
    query_sweep("point_cloud", 1)
    query_timestamp("point_cloud", 1, 2)
    query_classification("point_cloud", 1)
    query_classification("point_cloud", 2)